﻿using System;
using System.Reflection;
using ValidationEngine.Commons;
using ValidationEngine.Commons.Enums;
using ValidationEngine.Commons.Interfaces;
using ValidationEngine.Tools;

namespace ValidationEngine.ValidationRules
{
    class ValidGlobalCodeRule: BaseValidationRule
    {
        private object _browser;
        protected override IValidationInfo ApplyRule(IValidationContext ctx)
        {
            var code = ModelHelper.GetPropertyValue<string>(ctx);
            if (null != code)
            {
                if (!IsValidGlobalCode(code))
                {
                   DefResult = "Code is not unique.";
                }
            }
            return Result;
        }

        public ValidGlobalCodeRule(object browser, ValidationErrorType errorType = ValidationErrorType.Error)
        {
            this._browser = browser;
            this._defErrorType = errorType;
        }

        private bool IsValidGlobalCode(string code)
        {
            MethodInfo method = _browser.GetType().GetMethod("IsValidGlobalCode");
            if (null != method)
            {
                return (bool)method.Invoke(_browser, new object[] { code });
            }
            throw new InvalidOperationException("browser has no method IsValidGlobalCode");
        }
    }
}
